package com.dhcy.mqtt.service.impl;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dhcy.mqtt.dao.RevEquipmentDataMapper;
import com.dhcy.mqtt.model.RevEquipmentData;
import com.dhcy.mqtt.par.ht.RevEquipmentDataAddPar;
import com.dhcy.mqtt.par.ht.RevEquipmentDataListPar;
import com.dhcy.mqtt.result.ht.RevEquipmentDataResult;
import com.dhcy.mqtt.result.ht.RevEquipmentPushDto;
import com.dhcy.mqtt.result.ht.RevEquipmentResult;
import com.dhcy.mqtt.result.ht.TableResultData;
import com.dhcy.mqtt.service.RevEquipmentDataService;
import com.dhcy.mqtt.util.AppResultData;
import com.dhcy.mqtt.util.IsNull;
import com.dhcy.mqtt.util.OkhttpUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.text.SimpleDateFormat;
import java.util.*;

@Slf4j
@Service
public class RevEquipmentDataServiceImpl extends ServiceImpl<RevEquipmentDataMapper, RevEquipmentData> implements RevEquipmentDataService {
    @Autowired
    RevEquipmentDataMapper revEquipmentDataMapper;
    @Autowired
    OkhttpUtil okhttpUtil;

   static SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    /**
     * 添加设备数据
     *
     * @param revEquipmentDataaddPar
     * @return
     */
    @Override
    public AppResultData revEquipmentDataAdd(RevEquipmentDataAddPar revEquipmentDataaddPar) {

        if (IsNull.isNullOrEmpty(revEquipmentDataaddPar)) {
            return AppResultData.errorMessage("请求数据为空");
        }
        RevEquipmentData revEquipmentData = new RevEquipmentData();
        BeanUtils.copyProperties(revEquipmentDataaddPar, revEquipmentData);
        revEquipmentDataMapper.insert(revEquipmentData);
        if (!equipmentPush(revEquipmentData)){
            equipmentPush(revEquipmentData);
        }
        return AppResultData.successMessage("成功");
    }

    public static void main(String[] args) {
        String url = "http://build.dothis.cc/index/api/equipmentPush";

        RevEquipmentData revEquipmentData = new RevEquipmentData();
        revEquipmentData.setCode("01");
        revEquipmentData.setCreateTime(new Date());
        revEquipmentData.setNumber("0001");
        revEquipmentData.setValue("45405");
        revEquipmentData.setName("氚");
        revEquipmentData.setStatusCode("02");
        revEquipmentData.setStatusValue("超阈值");
        revEquipmentData.setCreateTime(new Date());
        RevEquipmentPushDto revEquipmentPushDto = new RevEquipmentPushDto();
        BeanUtil.copyProperties(revEquipmentData,revEquipmentPushDto);
        revEquipmentPushDto.setCreateTime(df.format(revEquipmentData.getCreateTime()));
        String s = JSONUtil.toJsonStr(revEquipmentPushDto);
        String body = HttpRequest.post(url).header("Content-Type","application/json").body(s).execute().body();
        System.out.println(body);
    }

    /**
     * 将数据推给久源数据
     * @param
     * @return
     */
    @Override
    public boolean equipmentPush(RevEquipmentData revEquipmentData){
        String url = "http://build.dothis.cc/index/api/equipmentPush";
        RevEquipmentPushDto revEquipmentPushDto = new RevEquipmentPushDto();
        BeanUtil.copyProperties(revEquipmentData,revEquipmentPushDto);
        revEquipmentPushDto.setCreateTime(df.format(revEquipmentData.getCreateTime()));
        String s = JSONUtil.toJsonStr(revEquipmentPushDto);
        String body = HttpRequest.post(url).header("Content-Type","application/json").body(s).execute().body();
        JSONObject parseObj = JSONUtil.parseObj(body);
        if (parseObj.getInt("type") > 2 ) {
            log.info("推送数据失败:{}", JSONUtil.toJsonStr(revEquipmentData));
            return false;
        }
        asynUpdateIsPush(Arrays.asList(revEquipmentData));
        return  true;
    }

    /**
     * 查询设备数据
     */
    @Override
    public TableResultData revEquipmentDataList(RevEquipmentDataListPar revEquipmentDataListPar) {
        IPage<RevEquipmentDataResult> page = new Page<>(revEquipmentDataListPar.getPage(), revEquipmentDataListPar.getPageSize());
        QueryWrapper<RevEquipmentData> queryWrapper = new QueryWrapper<>();
        if (!IsNull.isNullOrEmpty(revEquipmentDataListPar.getCode())) {
            queryWrapper.like(" code ", revEquipmentDataListPar.getCode());
        }
        if (!IsNull.isNullOrEmpty(revEquipmentDataListPar.getName())) {
            queryWrapper.like(" name ", revEquipmentDataListPar.getName());
        }
        if (!IsNull.isNullOrEmpty(revEquipmentDataListPar.getNumber())) {
            queryWrapper.like(" number ", revEquipmentDataListPar.getNumber());
        }
        if (!IsNull.isNullOrEmpty(revEquipmentDataListPar.getStatusCode())) {
            queryWrapper.like(" status_code  ", revEquipmentDataListPar.getStatusCode());
        }
        if (!IsNull.isNullOrEmpty(revEquipmentDataListPar.getStatusValue())) {
            queryWrapper.like(" status_value  ", revEquipmentDataListPar.getStatusValue());
        }
        if (!IsNull.isNullOrEmpty(revEquipmentDataListPar.getValue())) {
            queryWrapper.like(" value  ", revEquipmentDataListPar.getValue());
        }
        if (!IsNull.isNullOrEmpty(revEquipmentDataListPar.getUValue())) {
            queryWrapper.like(" u_value  ", revEquipmentDataListPar.getUValue());
        }
        if (!IsNull.isNullOrEmpty(revEquipmentDataListPar.getPuValue())) {
            queryWrapper.like(" pu_value  ", revEquipmentDataListPar.getPuValue());
        }
        queryWrapper.orderByDesc("id");
        List<RevEquipmentDataResult> resultList = revEquipmentDataMapper.list(page, queryWrapper);
        return TableResultData.success(page.getTotal(), resultList);

    }

    @Override
    public TableResultData lineChartDataList(RevEquipmentDataListPar revEquipmentDataListPar) {
        IPage<RevEquipmentDataResult> page = new Page<>(revEquipmentDataListPar.getPage(), revEquipmentDataListPar.getPageSize());
        QueryWrapper<RevEquipmentData> queryWrapper = new QueryWrapper<>();
        if (!IsNull.isNullOrEmpty(revEquipmentDataListPar.getCode())) {
            queryWrapper.like(" code ", revEquipmentDataListPar.getCode());
        }
        if (!IsNull.isNullOrEmpty(revEquipmentDataListPar.getName())) {
            queryWrapper.like(" name ", revEquipmentDataListPar.getName());
        }
        if (!IsNull.isNullOrEmpty(revEquipmentDataListPar.getNumber())) {
            queryWrapper.like(" number ", revEquipmentDataListPar.getNumber());
        }
        if (!IsNull.isNullOrEmpty(revEquipmentDataListPar.getStatusCode())) {
            queryWrapper.like(" status_code  ", revEquipmentDataListPar.getStatusCode());
        }
        if (!IsNull.isNullOrEmpty(revEquipmentDataListPar.getStatusValue())) {
            queryWrapper.like(" status_value  ", revEquipmentDataListPar.getStatusValue());
        }
        if (!IsNull.isNullOrEmpty(revEquipmentDataListPar.getValue())) {
            queryWrapper.like(" value  ", revEquipmentDataListPar.getValue());
        }
        if (!IsNull.isNullOrEmpty(revEquipmentDataListPar.getUValue())) {
            queryWrapper.like(" u_value  ", revEquipmentDataListPar.getUValue());
        }
        if (!IsNull.isNullOrEmpty(revEquipmentDataListPar.getPuValue())) {
            queryWrapper.like(" pu_value  ", revEquipmentDataListPar.getPuValue());
        }
        queryWrapper.orderByDesc("id");
        List<RevEquipmentDataResult> resultList = revEquipmentDataMapper.list(page, queryWrapper);
        Collections.reverse(resultList);
        return TableResultData.success(page.getTotal(), resultList);
    }

    /**
     * 久源数据同步
     * @param code
     * @param number
     * @return
     */
    @Override
    public AppResultData equipmentPush(String code, String number,Integer num) {
        if (ObjectUtil.isEmpty(code)){
            return AppResultData.errorMessage("code不能为空");
        }
        QueryWrapper<RevEquipmentData> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("code",code);
        if (ObjectUtil.isNotEmpty(number)){
            queryWrapper.eq("number",number);
        }
        if (ObjectUtil.isNotEmpty(num)){
            queryWrapper.last("limit 0,"+num);
        }
        queryWrapper.eq("is_push",false);
        queryWrapper.orderByAsc("id");
        List<RevEquipmentData> revEquipmentData = revEquipmentDataMapper.selectList(queryWrapper);
        if (ObjectUtil.isNotEmpty(revEquipmentData)){
            asynUpdateIsPush(revEquipmentData);
        }
        List<RevEquipmentResult> revEquipmentResults = BeanUtil.copyToList(revEquipmentData, RevEquipmentResult.class);
        return AppResultData.successData(revEquipmentResults);
    }

    /**
     * 异步修改数据推送状态
     * @param list
     */
    @Async
     void asynUpdateIsPush(List<RevEquipmentData> list){
        list.stream().forEach(item->{item.setIsPush(true);});
        boolean b = updateBatchById(list);
    }
}
